package com.sls.mall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sls.common.to.mq.SeckillOrderTo;
import com.sls.common.utils.R;
import com.sls.common.vo.MemberRespVo;
import com.sls.mall.seckill.feign.CouponFeignService;
import com.sls.mall.seckill.feign.ProductFeignService;
import com.sls.mall.seckill.interceptor.LoginInterceptor;
import com.sls.mall.seckill.service.SeckillService;
import com.sls.mall.seckill.to.SeckillSkuRedisTo;
import com.sls.mall.seckill.vo.SeckillSessionWithSkusVo;
import com.sls.mall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、扫描最近三天的商品需要参加秒杀的活动
        R lates3DaySession = couponFeignService.getLates3DaySession();
        log.info("秒杀扫描结果：" + lates3DaySession);
        if (lates3DaySession.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkusVo> sessionData = lates3DaySession.getData("data", new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException bx) {
        log.error("getCurrentSeckillSkusResouse被限流了。。。");
        return  null;
    }

    @SentinelResource(value = "getCurrentSeckillSkusResouse", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        try(Entry entry = SphU.entry("seckillSkus")){
            //1、确定当前属于哪个秒杀场次
            long currentTime = System.currentTimeMillis();
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long startTime = Long.parseLong(s[0]);
                long endTime = Long.parseLong(s[1]);
                // 判断是否是否是当前秒杀档次
                if (currentTime >= startTime && currentTime <= endTime) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hasOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                    assert range != null;
                    List<String> listValue = hasOps.multiGet(range);
                    if (listValue != null && listValue.size() >= 0) {

                        List<SeckillSkuRedisTo> collect = listValue.stream().map(item -> {
                            String items = (String) item;
                            SeckillSkuRedisTo redisTo = JSON.parseObject(items, SeckillSkuRedisTo.class);
                            // redisTo.setRandomCode(null);当前秒杀开始需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        log.info("......" + collect);
                        return collect;
                    }
                    break;
                }
            }
        } catch (Exception e){
            log.error("资源被限流，{}", e.getMessage());
        }


        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSecillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    String redisValue = hashOps.get(key);
                    SeckillSkuRedisTo to = JSON.parseObject(redisValue, SeckillSkuRedisTo.class);
                    long currentTime = System.currentTimeMillis();
                    //如果当前时间大于等于秒杀活动开始时间并且要小于活动结束时间
                    if (currentTime >= to.getStartTime() && currentTime <= to.getEndTime()) {
                        return to;
                    }
                    to.setRandomCode(null);
                    return to;
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        long s1 = System.currentTimeMillis();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        if (hashOps != null) {
            String json = hashOps.get(killId);
            if (json == null) {
                return null;
            }
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long time = new Date().getTime();
            // 1.校验时间合法性
            if (time >= startTime && time <= endTime) {
                // 2.校验随机码
                if (skuRedisTo.getRandomCode().equals(key)) {
                    // 3.校验秒杀数量是否合理
                    if (num <= skuRedisTo.getSeckillLimit()) {
                        // 4.验证当前客户是否已经购买过，幂等性；秒杀成功就去占位（userId_sessionId_skuId）
                        String redisKey = memberRespVo.getId() + "_" + killId;
                        //设置自动过期(活动结束时间-当前时间)
                        Long ttl = endTime - time;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        if(aBoolean){
                            //占位成功说明从来没有买过,分布式锁(获取信号量-1)
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + skuRedisTo.getRandomCode());
                            boolean b = semaphore.tryAcquire(num);
                            if(b){
                                // 秒杀成功，快速下单 发送MQ消息
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(orderSn);
                                orderTo.setMemberId(memberRespVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                orderTo.setSkuId(skuRedisTo.getSkuId());
                                orderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("耗时..." + (s2 - s1));
                                return orderSn;
                            }
                        } else {
                            return null;
                        }
                    }
                }
            } else {
                return null;
            }
        }
        long s3 = System.currentTimeMillis();
        log.info("耗时..." + (s3 - s1));
        return null;
    }

    /**
     * 换成活动sku信息
     *
     * @param sessionData
     */
    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> sessionData) {
        sessionData.forEach(session -> {
            BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
            session.getRelationSkus().forEach(seckillSkuVo -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                String redisKey = seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString();

                if (!hashOperations.hasKey(redisKey)) {
                    SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();
                    // 获取sku信息
                    R r = productFeignService.getSukInfo(seckillSkuVo.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfo(skuInfo);
                    }
                    // 封装sku 的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, skuRedisTo);
                    // 设置当前秒杀产品的时间信息
                    skuRedisTo.setStartTime(session.getStartTime().getTime());
                    skuRedisTo.setEndTime(session.getEndTime().getTime());

                    // 设置商品的随机码 防止篡改
                    skuRedisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(skuRedisTo);
                    hashOperations.put(redisKey, jsonString);

                    //5、使用库存作为分布式Redisson信号量（限流）
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }

    /**
     * 缓存活动信息
     *
     * @param sessionData
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessionData) {
        sessionData.forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> skuIds = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });
    }
}
